import { resultFailure, resultSuccess } from '@utils/resultFormatter'
import { prisma } from '@repos/index.repo'

/**
 * ==================== EventInstance 管理 ====================
 * 管理事件实例（单独管理，不创建 EventRecord）
 */

/**
 * 创建事件实例（不创建 EventRecord）
 * @param eventId 事件ID
 * @param memberId 成员ID
 * @param organizationId 组织ID
 * @param isCycle 是否为周期性事件
 */
export const createEventInstance = async (
    eventId: string,
    memberId: string,
    organizationId: string,
    isCycle: boolean = false
) => {
    try {
        const result = await prisma.eventInstance.create({
            data: {
                eventId,
                memberId,
                organizationId,
                isCycle
            },
            include: {
                event: {
                    include: {
                        EventSetting: true
                    }
                },
                member: {
                    select: {
                        id: true,
                        identifier: true,
                        realName: true,
                        nickName: true
                    }
                }
            }
        })

        return resultSuccess(true, 201, result, 'Event instance created successfully')
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 批量创建事件实例
 * @param eventId 事件ID
 * @param memberIds 成员ID列表
 * @param organizationId 组织ID
 * @param isCycle 是否为周期性事件
 */
export const createEventInstanceBatch = async (
    eventId: string,
    memberIds: string[],
    organizationId: string,
    isCycle: boolean = false
) => {
    try {
        const result = await prisma.eventInstance.createMany({
            data: memberIds.map(memberId => ({
                eventId,
                memberId,
                organizationId,
                isCycle
            })),
            skipDuplicates: true
        })

        return resultSuccess(true, 201, result, `${result.count} event instances created successfully`)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 删除事件实例（软删除）
 * @param instanceId 事件实例ID
 */
export const deleteEventInstance = async (instanceId: string) => {
    try {
        const result = await prisma.eventInstance.update({
            where: { id: instanceId },
            data: {
                deletedAt: new Date()
            }
        })

        if (!result) return resultFailure(false, 404, 'Event instance not found')

        return resultSuccess(true, 200, result, 'Event instance deleted successfully')
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取单个事件实例
 * @param instanceId 事件实例ID
 */
export const readEventInstance = async (instanceId: string) => {
    try {
        const result = await prisma.eventInstance.findUnique({
            where: { id: instanceId },
            include: {
                event: {
                    include: {
                        EventSetting: true,
                        organization: true
                    }
                },
                member: {
                    select: {
                        id: true,
                        identifier: true,
                        realName: true,
                        nickName: true,
                        wxOpenId: true
                    }
                },
                EventRecord: true
            }
        })

        if (!result) return resultFailure(false, 404, 'Event instance not found')

        return resultSuccess(true, 200, result)
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取事件实例列表
 * @param filters 过滤条件
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readEventInstanceList = async (
    filters: {
        eventId?: string
        memberId?: string
        organizationId?: string
        isCycle?: boolean
    } = {},
    offset: number = 0,
    limit: number = 10
) => {
    try {
        const whereClause: any = {
            deletedAt: null
        }

        if (filters.eventId) whereClause.eventId = filters.eventId
        if (filters.memberId) whereClause.memberId = filters.memberId
        if (filters.organizationId) whereClause.organizationId = filters.organizationId
        if (filters.isCycle !== undefined) whereClause.isCycle = filters.isCycle

        const total = await prisma.eventInstance.count({
            where: whereClause
        })

        const result = await prisma.eventInstance.findMany({
            where: whereClause,
            skip: offset,
            take: limit,
            orderBy: {
                createdAt: 'desc'
            },
            include: {
                event: {
                    select: {
                        id: true,
                        title: true,
                        startAt: true,
                        endAt: true
                    }
                },
                member: {
                    select: {
                        id: true,
                        identifier: true,
                        realName: true,
                        nickName: true
                    }
                },
                EventRecord: {
                    select: {
                        id: true,
                        record: true,
                        createdAt: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取某个事件的所有实例
 * @param eventId 事件ID
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readEventInstancesByEvent = async (eventId: string, offset: number = 0, limit: number = 10) => {
    try {
        const total = await prisma.eventInstance.count({
            where: { eventId, deletedAt: null }
        })

        const result = await prisma.eventInstance.findMany({
            where: { eventId, deletedAt: null },
            skip: offset,
            take: limit,
            orderBy: {
                createdAt: 'desc'
            },
            include: {
                member: {
                    select: {
                        id: true,
                        identifier: true,
                        realName: true,
                        nickName: true
                    }
                },
                EventRecord: {
                    select: {
                        id: true,
                        record: true,
                        data: true,
                        createdAt: true,
                        updatedAt: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 读取某个成员的所有事件实例
 * @param memberId 成员ID
 * @param offset 偏移量
 * @param limit 限制数量
 */
export const readEventInstancesByMember = async (memberId: string, offset: number = 0, limit: number = 10) => {
    try {
        const total = await prisma.eventInstance.count({
            where: { memberId, deletedAt: null }
        })

        const result = await prisma.eventInstance.findMany({
            where: { memberId, deletedAt: null },
            skip: offset,
            take: limit,
            orderBy: {
                createdAt: 'desc'
            },
            include: {
                event: {
                    select: {
                        id: true,
                        title: true,
                        description: true,
                        startAt: true,
                        endAt: true
                    }
                },
                EventRecord: {
                    select: {
                        id: true,
                        record: true,
                        data: true,
                        createdAt: true
                    }
                }
            }
        })

        return resultSuccess(true, 200, { total, result })
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 检查事件实例是否存在
 * @param instanceId 事件实例ID
 */
export const checkEventInstanceExists = async (instanceId: string) => {
    try {
        const result = await prisma.eventInstance.findUnique({
            where: { id: instanceId }
        })

        if (!result) return resultFailure(false, 404, 'Event instance not found')

        return resultSuccess(true, 200, true, 'Event instance exists')
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}

/**
 * 获取事件实例统计信息
 * @param eventId 事件ID
 */
export const getEventInstanceStatistics = async (eventId: string) => {
    try {
        const total = await prisma.eventInstance.count({
            where: { eventId, deletedAt: null }
        })

        const withRecord = await prisma.eventInstance.count({
            where: {
                eventId,
                deletedAt: null,
                EventRecord: {
                    isNot: null
                }
            }
        })

        const withoutRecord = total - withRecord

        const cycleInstances = await prisma.eventInstance.count({
            where: {
                eventId,
                deletedAt: null,
                isCycle: true
            }
        })

        return resultSuccess(
            true,
            200,
            {
                total,
                withRecord,
                withoutRecord,
                cycleInstances
            },
            'Event instance statistics retrieved successfully'
        )
    } catch (err) {
        return resultFailure(false, 500, String(err))
    }
}
